package com.changgou.oauth.config;

import com.changgou.entity.Result;
import com.changgou.user.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/***
 * 描述
 * @author ljh
 * @packagename com.itheima.config
 * @version 1.0
 * @date 2020/1/10
 */
@Component
//如果我们要从数据库动态查询用户信息，
// 就必须按照spring security框架的要求提供一个实现UserDetailsService接口的实现类，
// 并按照框架的要求进行配置即可。框架会自动调用实现类中的方法并自动进行密码校验。
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("获取到的用户名是：" + username);
        Result<com.changgou.user.pojo.User> userResult = userFeign.loadById(username);
        com.changgou.user.pojo.User user = userResult.getData();
        if(user==null){
            System.out.println("用户为空");
            return null;
        }
        String password = user.getPassword();
//       也可以自己设定一些固定的权限list进去
// List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
////授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
//        list.add(new SimpleGrantedAuthority("add")); // 权限
//        list.add(new SimpleGrantedAuthority("delete")); // 权限
//        list.add(new SimpleGrantedAuthority("ROLE_ADMIN")); // 角色
        String permission = "ROLE_ADMIN,ROLE_USER";//设置权限
        //框架底层已经实现了根据username查询密码,传usernam进去就会自动匹配
        /*return new User(username, passwordEncoder.encode(password),  //user表里的账号和密码
                AuthorityUtils.commaSeparatedStringToAuthorityList(permission));*/

        return new User(username, password,  //注意这里不需要再加密了 给spring-security校验密码是否ok
                AuthorityUtils.commaSeparatedStringToAuthorityList(permission));
    }
}
